package cn.topevery.garden.dal.logic;

import cn.hutool.core.bean.BeanUtil;
import cn.topevery.garden.dal.dao.GreTreeFamousDao;
import cn.topevery.garden.dal.util.ExcelImportUtil;
import cn.topevery.garden.entity.po.GreTreeFamous;
import cn.topevery.garden.entity.query.GreTreeFamousQuery;
import cn.topevery.garden.entity.query.GreTreeFamousRecordQuery;
import cn.topevery.garden.entity.vo.GreTreeFamousRecordVO;
import cn.topevery.garden.entity.vo.GreTreeFamousVO;
import cn.topevery.garden.framework.base.BaseLogic;
import hw.topevery.basis.dal.logic.SysDeptLogic;
import hw.topevery.basis.dal.util.SysMapTreeUtil;
import hw.topevery.basis.entity.po.SysDept;
import hw.topevery.basis.runtime.UserRuntime;
import hw.topevery.framework.db.base.BaseEntityDao;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.web.JsonResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.function.Predicate;

/**
 * 古树名木表
 *
 * @author code-generate
 * @date 2022-01-05
 */
@Service
public class GreTreeFamousLogic extends BaseLogic<GreTreeFamous> {
    @Autowired
    GreTreeFamousDao greTreeFamousDao;

    @Override
    public BaseEntityDao<GreTreeFamous, Integer> getDao() {
        return greTreeFamousDao;
    }


    /**
     * 获取列表
     *
     * @param query
     */
    public DataPager<GreTreeFamousVO> listPage(GreTreeFamousQuery query) {
        return greTreeFamousDao.listPage(query);
    }

    /**
     * 根据自增id批量删除
     *
     * @param ids
     */
    public void deleteBatchById(String userId, Integer[] ids) {
        greTreeFamousDao.delete(userId, ids);
    }

    /**
     * 根据自增id保存或者更新
     *
     * @param greTreeFamous 实体
     */
    public void saveOrUpdate(String userId, GreTreeFamous greTreeFamous) {
        greTreeFamousDao.saveOrUpdate(userId, greTreeFamous);
    }

    public GreTreeFamous insertEntity(String userId, GreTreeFamous greTreeFamous) {
        return greTreeFamousDao.insertEntity(userId, greTreeFamous);
    }

    /**
     * 根据自定义列值来获取对象
     */
    public GreTreeFamous getEntityByColumn(String key, String value) {
        return greTreeFamousDao.getEntityByColumn(key, value);
    }

    public DataPager<Map> getList(DataPager<Map> page, Map map) {
        return greTreeFamousDao.getList(page, map);
    }

    public DataPager<GreTreeFamousRecordVO> getRecordList(GreTreeFamousRecordQuery greTreeFamousRecordQuery) {
        return greTreeFamousDao.getRecordList(greTreeFamousRecordQuery);
    }

    public void deleteByIds(List<String> ids, Integer userId) {
        greTreeFamousDao.deleteByIds(ids, userId);
    }

    public void update(GreTreeFamous greTreeFamous, Integer userId) {
        greTreeFamousDao.update(greTreeFamous, userId);
    }

    public void dataPublics(List<Integer> ids, Integer userId) {
        greTreeFamousDao.dataPublics(ids, userId);
    }

    public void insert(GreTreeFamous greTreeFamous, Integer userId) {
        greTreeFamousDao.insert(greTreeFamous, userId);
    }

    public GreTreeFamous getById(Integer id) {
        return greTreeFamousDao.getById(id);
    }

    public void insertSql(GreTreeFamous greTreeFamous) {
        greTreeFamousDao.insertSql(greTreeFamous);
    }

    public Map<String, Object> getSituation() {
        return greTreeFamousDao.getSituation();
    }

    public List<Map<String, Object>> getAreaCountStat() {
        return greTreeFamousDao.getAreaCountStat();
    }

    public List<Map<String, Object>> listMaps() {
        return greTreeFamousDao.listMaps();
    }


    public Integer updateAge(Integer year) {
        return greTreeFamousDao.updateAge(year);
    }

    public void updateFamousType() {
        greTreeFamousDao.updateFamousType();
    }

    public List<Map<String, Object>> getAllTreeFamousForMap(int famous_type_id) {
        return greTreeFamousDao.getAllTreeFamousForMap(famous_type_id);
    }

    public List<GreTreeFamous> getListByCommunityCode(String communityCode, String name) {
        return greTreeFamousDao.getListByCommunityCode(communityCode, name);
    }

    public GreTreeFamous getByCommunityCodeAndCode(String communityCode, String code) {
        return greTreeFamousDao.getByCommunityCodeAndCode(communityCode, code);
    }

    /**
     * 按类型查后备资源（导出二维码使用）
     *
     * @param type 1:群落 2:散生
     * @return
     */
    public List<GreTreeFamous> getListForQRCode(Integer type) {
        return greTreeFamousDao.getListForQRCode(type);
    }

    @Autowired
    private SysMapTreeUtil sysMapTreeUtil;

    @Autowired
    private SysDeptLogic sysDeptLogic;

    public JsonResult<?> analysisExcel(MultipartFile file) {
        try {
            Map<String, Object> map = ExcelImportUtil.analysisExcel(file.getInputStream(), GreTreeFamousVO.class, filterFunc());
            return JsonResult.ok(map);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error("解析发生错误，请按照模板格式填写数据！");
        }
    }

    public JsonResult<?> importExcel(List<GreTreeFamousVO> treeFamousVOList) {
        return ExcelImportUtil.importExcel(treeFamousVOList, filterFunc(),
                vo -> BeanUtil.copyProperties(vo, GreTreeFamous.class),
                entities -> greTreeFamousDao.insert(UserRuntime.getSysUser().id.toString(), entities));
    }

    public Predicate<GreTreeFamousVO> filterFunc() {
        return vo -> {
            //校验必填项
            if (StringUtils.isBlank(vo.getCode()) || StringUtils.isBlank(vo.getCode())) {
                vo.setErrorMessage("编号或名称为空\t");
                return true;
            }
            //校验行政区域
            StringBuilder errorMessageBuilder = new StringBuilder();
            boolean areaFlag = ExcelImportUtil.verifyArea(vo, errorMessageBuilder, sysMapTreeUtil);
            boolean deptFlag = false;
            //校验责任单位和巡护单位
            if (StringUtils.isNotBlank(vo.getManage())) {
                SysDept manage = sysDeptLogic.getDeptByName(vo.getManage());
                if (manage == null) {
                    deptFlag = true;
                    errorMessageBuilder.append("所填所填责任单位不存在\t");
                } else {
                    vo.setManageId(manage.deptId);
                }
            }
            if (StringUtils.isNotBlank(vo.getMaintainDept())) {
                SysDept maintain = sysDeptLogic.getDeptByName(vo.getMaintainDept());
                if (maintain == null) {
                    deptFlag = true;
                    errorMessageBuilder.append("所填巡护单位不存在\t");
                } else {
                    vo.setMaintainDeptId(maintain.deptId);
                }
            }
            vo.setErrorMessage(errorMessageBuilder.toString());
            return areaFlag || deptFlag;
        };
    }
}
